<?php

/**
 * This is the model class for table "{{auth_item}}".
 *
 * The followings are the available columns in table '{{auth_item}}':
 * @property integer $id
 * @property string $name
 * @property string $type
 * @property string $description
 * @property string $bizrule
 * @property string $data
 *
 * The followings are the available model relations:
 * @property AuthAssignment[] $authAssignments
 * @property AuthItemtype $type0
 * @property AuthItemchild[] $authItemchildren
 * @property AuthItemchild[] $authItemchildren1
 */
class AuthItem extends CActiveRecord
{

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return AuthItem the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{auth_item}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('name, type', 'required', 'message' => t('MSG_REQUIRED','messages')),
            array('name', 'length', 'max' => 64, 'tooLong' => t('MSG_STRING_TOO_LONG', 'messages')),
            array('type', 'length', 'max' => 11, 'tooLong' => t('MSG_STRING_TOO_LONG', 'messages')),
            array('description, bizrule, data', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, name, type, description, bizrule, data', 'safe', 'on' => 'search'),
            array('name', 'unique', 'message' => t('MSG_UNIQUE', 'messages')),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'yiiUsers' => array(self::MANY_MANY, 'User', '{{auth_assignment}}(itemname, userid)'),
            'authAssignments' => array(self::HAS_MANY, 'AuthAssignment', 'itemname'),
            'type0' => array(self::BELONGS_TO, 'AuthItemtype', 'type'),
            'authItemchildren' => array(self::HAS_MANY, 'AuthItemchild', 'parent'),
            'authItemchildren1' => array(self::HAS_MANY, 'AuthItemchild', 'child'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => t('LBL_ID', 'authItem'),
            'name' => t('LBL_NAME', 'authItem'),
            'type' => t('LBL_TYPE', 'authItem'),
            'description' => t('LBL_DESCRIPTION', 'authItem'),
            'bizrule' => t('LBL_BIZRULE', 'authItem'),
            'data' => t('LBL_DATA', 'authItem'),
            'updated_by' => t('LBL_UPDATEBY', 'authItem'),
            'update_date' => t('LBL_UPDATE_DATE', 'authItem'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('type', $this->type, true);
        $criteria->compare('description', $this->description, true);
        $criteria->compare('bizrule', $this->bizrule, true);
        $criteria->compare('data', $this->data, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                    'pagination' => array(
                        'pageSize' => LGHelpers::getPageSize($this->count()),
                    ),
                    'sort' => array(
                        'defaultOrder' => array(
                            'name' => CSort::SORT_ASC,
                            'type' => CSort::SORT_ASC,
                        )
                    ),
                ));
    }

    public function beforeSave()
    {
        if (parent::beforeSave())
        {
            $current_date = date(LGConstant::DATE_FORMAT_FOR_DATABASE);
            $logedInUser = User::model()->findByPk(Yii::app()->user->id);
//            if ($this->created_date == NULL)
//            {
//                $this->created_date = $current_date;
//                $this->update_date = $current_date;
//                $this->updated_by = $logedInUser->username;
//            }
//            else
//            {
//                $this->update_date = $current_date;
//                $this->updated_by = $logedInUser->username;
//            }

            if ($this->create_date == NULL)
            {
                $this->create_date = $current_date;
            }

            if ($this->created_by == NULL)
            {
                $this->created_by = $logedInUser->username;
            }

            $this->update_date = $current_date;
            $this->updated_by = $logedInUser->username;


            return true;
        }
        else
            return false;
    }

    protected function afterFind()
    {
        // convert to display format
        $this->update_date = strtotime($this->update_date);
        $this->update_date = date(LGConstant::DATE_FORMAT, $this->update_date);
        if ($this->update_date == LGConstant::DATE_DEFAULT)
            $this->update_date = '';

        parent::afterFind();
    }

    public function getNameByType($type , $encodeLabel = false)
    {
        $names = $this->findAll('type=:_type', array(':_type' => $type));
        
        if ($encodeLabel)
        {
            $list = array();
            foreach ($names as $name){
                $obj = (object) array('key' => $name->name, 'value' => CHtml::encode($name->name));
                array_push($list, $obj);
            }
            return CHtml::listData($list, 'key', 'value');
        }
        else{
            return CHtml::listData($names, 'name', 'name');
        }
    }
    
    public function getNameByTypeForForm($type)
    {
        $user = User::model()->findByPk(user()->id);
        $names = $this->findAll('type=:_type', array(':_type' => $type));
        for ($i = 0 ; $i < count($names); $i++) {
            if(!$user->isSuperAdmin() && (trim(strtolower($names[$i]->name)) == strtolower(Roles::SUPER_ADMIN)
|| (!$user->isAdmin() && trim(strtolower($names[$i]->name)) == strtolower(LGConstantUserRole::ADMIN)))){
                    unset($names[$i]);
       
            }
        }
        return CHtml::listData($names, 'name', 'name');
    }
        
    public function getAllController()
    {
        $declaredClasses = get_declared_classes();
        foreach (glob(Yii::getPathOfAlias('application.controllers') . "/*Controller.php") as $controller)
        {
            $class = basename($controller, ".php");
            if (!in_array($class, $declaredClasses))
                Yii::import("application.controllers." . $class, true);
        }
        $declaredClasses = get_declared_classes();

        $controllers = array();
        foreach ($declaredClasses as $key => $value)
        {
            if (strlen(strstr($value, 'Controller')) > 0)
            {
                if ($value != 'CBaseController' && $value != 'CController' && $value != 'AdminController' )
                {
                    $value = str_replace('Controller', '', $value);
                    $controllers[$value] = $value;
                }
            }
        }
        return $controllers;
    }

}